package com.open.database;

import com.open.model.DataSource;
import com.open.utils.YamlUtil;
import lombok.extern.slf4j.Slf4j;

import java.sql.*;

/**
 * @author dashu
 * @date 2020-01-13 20:16
 * @description 数据库连接
 */
@Slf4j
public class DBConnection {

    private static DataSource dataSource;

    //初始化数据库连接
    static {
        try {
            dataSource = YamlUtil.loadConfig(DataSource.class, "application.yml");
            Class.forName(dataSource.getDriver());
        } catch (Exception e) {
            log.error("init db property fail", e);
        }
    }

    /**
     * 获取数据库连接
     *
     * @return
     * @throws SQLException
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(dataSource.getUrl(), dataSource.getUsername(), dataSource.getPassword());
    }


    /**
     * 数据库资源释放
     *
     * @param conn 数据库连接 Connection
     * @param st   Statement
     * @param rs   ResultSet
     */
    public static void closeResource(Connection conn, Statement st, ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            log.error("closeResource fail", e);
        }
    }

}